package cn.tpshion.vm.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.tpshion.vm.common.model.Result;
import cn.tpshion.vm.domain.dto.auth.LoginDTO;
import cn.tpshion.vm.service.UserService;
import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public Result<String> login(@Valid @RequestBody LoginDTO dto){
        userService.checkUser(dto);
        StpUtil.login(dto.getUsername());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        log.info("login tokenInfo:{}", JSON.toJSONString(tokenInfo));
        return Result.ok(tokenInfo.getTokenValue());
    }

    @PostMapping("/logout")
    public Result logout(){
        StpUtil.logout();
        return Result.ok();
    }
}
